package Controller.AdminUser;

import Models.dao.AdminUserDao;
import Models.enity.AdminUser;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/changePass")
public class ChangePassword extends HttpServlet {
    private static String PublicPath = "/WEB-INF/views";
    private AdminUserDao userDao = new AdminUserDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(PublicPath + "/admin_user/changePass.jsp").forward(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String oldPass = req.getParameter("oldPass");
        AdminUser user = (AdminUser)req.getSession().getAttribute("user");
        String id = user.getId().toString();
        String nowPass = req.getSession().getAttribute("user_pass").toString();
        String newPass = req.getParameter("newPass");
        String newPassConfirm = req.getParameter("newPassConfirm");
        if (!oldPass.equals(nowPass)){
            req.setAttribute("message","旧密码输入错误");
            req.getRequestDispatcher(PublicPath + "/admin_user/changePass.jsp").forward(req,resp);
        }
        if (!newPass.equals(newPassConfirm)){
            req.setAttribute("message","两次输入不一致");
            req.getRequestDispatcher(PublicPath + "/admin_user/changePass.jsp").forward(req,resp);
        }
        int tmp = userDao.ChangePassword(id,newPass);
        if(tmp != -1){
            resp.sendRedirect("/index");
        }else {
            req.setAttribute("message","修改失败,数据库错误！");
            req.getRequestDispatcher(PublicPath + "/admin_user/changePass.jsp").forward(req,resp);
        }
    }
}
